#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>


//计算一个目录下的普通文件个数。(考虑子目录)
/*
    返回值：
        成功 普通文件的个数 >=0
        失败 返回-1
*/
int Get_num_dir(char*dir_pathname)// ./dir
{
    //打开目录
    DIR* dir = opendir(dir_pathname);
    if(dir == NULL)
    {
        printf("open %s error:%s\n", dir_pathname, strerror(errno));
        return -1;
    }
    
    int count = 0;
    //读取目录
    struct dirent*p = NULL;
    while(p = readdir(dir))
    {
        //过滤 . 和 ..
        if(strcmp(p->d_name,".") == 0 || strcmp(p->d_name,"..") == 0)
        {
            continue;
        }
        
        if(p->d_type == DT_DIR)
        {
            char pathname[128] = {0};
            strcpy(pathname, dir_pathname);
            //pathname[strlen(pathname)] = '/';
            //strcpy(pathname+strlen(pathname), p->d_name);
            strcat(pathname,"/");
            strcat(pathname,p->d_name);
            count += Get_num_dir(pathname);
        }
        else if(p->d_type == DT_REG)
        {
            count++;
        }
    }
    if(errno != 0)
        return -1;

    //关闭目录
    closedir(dir);
    return count;
}
//写一个函数，求一个目录的大小（所有（包含子目录）普通文件的文件大小之和）
/*
    返回值：
        成功 文件大小 >=0
        失败 返回-1
*/
int Get_size_dir(char*dir_pathname)// ./dir
{
    //打开目录
    DIR* dir = opendir(dir_pathname);
    if(dir == NULL)
    {
        printf("open %s error:%s\n", dir_pathname, strerror(errno));
        return -1;
    }
    
    int size = 0;
    //读取目录
    struct dirent*p = NULL;
    while(p = readdir(dir))
    {
        //过滤 . 和 ..
        if(strcmp(p->d_name,".") == 0 || strcmp(p->d_name,"..") == 0)
        {
            continue;
        }
        //合并子文件与父目录的路径
        char pathname[128] = {0};
        strcpy(pathname, dir_pathname);
        //pathname[strlen(pathname)] = '/';
        //strcpy(pathname+strlen(pathname), p->d_name);
        strcat(pathname,"/");
        strcat(pathname,p->d_name);
        if(p->d_type == DT_DIR)
        {
            size += Get_size_dir(pathname);
        }
        else if(p->d_type == DT_REG)
        {
            struct stat st;
            if(lstat(pathname, &st) == -1)
            {
                break;
            }
            size += st.st_size;
        }
    }
    if(errno != 0)
        return -1;

    //关闭目录
    closedir(dir);
    return size;
}
int main(int argc, char**argv)
{
    int count = Get_num_dir(argv[1]);//
    printf("%s:%d\n", argv[1], count);

    int size = Get_size_dir(argv[1]);
    printf("size = %d\n", size);
}